package com.aeromedia.testcustomapplication.recyclerVIew;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;


import androidx.recyclerview.widget.RecyclerView;

public abstract class CommonAdapter<DATA> extends RecyclerView.Adapter<CommonHolder> {
    private int resID;
    private ResType resType;
    private Context mContext;
    private LayoutInflater inflater;
    List<DATA> data;

    public CommonAdapter(Context context, int resID) {
        mContext = context;
        inflater = LayoutInflater.from(context);
        this.resID = resID;
    }

    public CommonAdapter(Context context, ResType resType) {
        mContext = context;
        inflater = LayoutInflater.from(context);
        this.resType = resType;
    }

    public List<DATA> getData() {
        return data;
    }

    private static final String TAG = "CommonAdapter";
    public void setData(List<DATA> data) {
        this.data = data;
        Log.d(TAG, "setData: "+data.size());
        notifyDataSetChanged();
    }


    @Override
    public CommonHolder onCreateViewHolder( ViewGroup parent, int viewType) {
        if (resType != null) {
            resID = resType.getResId();
        }
        View inflate = inflater.inflate(resID, parent, false);
        return new CommonHolder(inflate);
    }

    @Override
    public void onBindViewHolder( CommonHolder holder, int position) {
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    mListener.onClick(data.get(holder.getAdapterPosition()), holder.getAdapterPosition());
                }
            }
        });
        bindData(holder, data.get(position));
    }

    protected abstract void bindData(CommonHolder holder, DATA data);

    @Override
    public int getItemCount() {
        return data.size();
    }

    private ItemClickListener<DATA> mListener;

    public void setItemClickListener(ItemClickListener<DATA> listener) {
        mListener = listener;
    }
}
